package com.lbb.waimai.Interceptor;

import com.lbb.waimai.entiry.Admin;
import com.lbb.waimai.entiry.User;
import com.lbb.waimai.service.AdminService;
import com.lbb.waimai.service.UserService;
import com.lbb.waimai.utils.JwtHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class PermissionVerificationInterceptor implements HandlerInterceptor {

    @Autowired

    private UserService userService;

    @Autowired
    private AdminService adminService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
//        if ("OPTIONS".equals(request.getMethod().toString())) {
//            return true; //true是直接放行，前端抓包会有options请求
//            //false拒接访问，抓包就不会有options请求了
//        }
        String requestURI = request.getRequestURI();
        System.out.println("============" + requestURI + "============");
        String substring = requestURI.substring(0, 6);
        if (substring.equals("/admin")) {
            Long userId = JwtHelper.getUserId(request);
            if (userId == null) {
                return false;
            }
            Integer integerId = Integer.valueOf(userId.toString());
            Admin admin = adminService.getById(integerId);
            return admin != null;
        } else {
            Long userId = JwtHelper.getUserId(request);
            if (userId == null) {
                return false;
            }
            Integer integerId = Integer.valueOf(userId.toString());
            User user = userService.getById(integerId);
            return user != null;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
